<!-- 课程基本信息 -->
<template>
    <div>
        <el-form ref="form" :model="course" label-width="80px">
            <el-form-item label="标题">
                <el-input v-model="course.title" style="width:20%"></el-input>
            </el-form-item>
            <el-form-item label="讲师">
                <el-select
                    v-model="course.teacherId"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="老师姓名"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    style="width:20%"
                    @change="teacherChange"
                >
                    <el-option
                        v-for="item in teachers"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                        <span style="float: left">
                            <el-tooltip placement="top">
                                <div slot="content">
                                    <el-image
                                        style="width: 150px; height: 150px"
                                        :src="item.avatar"
                                        fit="contain"
                                    ></el-image>
                                </div>
                                <el-avatar :size="30" fit="contain" :src="item.avatar"></el-avatar>
                            </el-tooltip>
                        </span>
                        <span>{{ item.name }}</span>
                        <span
                            style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.career }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="分类">
                <el-select
                    style="width:20%"
                    v-model="course.subjectParentId"
                    placeholder="大分类"
                    clearable
                    filterable
                    @change="parentSubjectChange"
                    @clear="childSubjects=[];course.subjectId=''"
                >
                    <el-option
                        v-for="item in subjects"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id"
                    ></el-option>
                </el-select>
                <el-select
                    style="width:20%"
                    v-model="course.subjectId"
                    placeholder="小分类"
                    clearable
                    filterable
                >
                    <el-option
                        v-for="item in childSubjects"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="价格" v-if="!classId">
                <el-input-number
                    style="width:20%"
                    v-model="course.price"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    controls-position="right"
                ></el-input-number>
            </el-form-item>
            <el-form-item label="课时">
                <el-input-number
                    v-model="course.lessonNum"
                    :min="0"
                    style="width:20%"
                    controls-position="right"
                ></el-input-number>
            </el-form-item>
            <el-form-item label="描述">
                <tinymce v-model="course.description" :height="300" :width="800" />
            </el-form-item>
            <el-form-item label="封面">
                <el-upload
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :action="BASE_API"
                    class="avatar-uploader"
                >
                    <el-image style="width: 500px; height: 300px" :src="course.cover" fit="contain">
                        <div slot="error" class="image-slot">
                            <el-image
                                style="width: 500px; height: 300px"
                                src="/src/assets/image-not-found.png"
                                fit="contain"
                            ></el-image>
                        </div>
                    </el-image>
                </el-upload>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Tinymce from "@/components/Tinymce";
import { getSubject } from "@/api/course/subject";
import { getTeacherByName, getById } from "@/api/ucenter/teacher";
import { getCourseById, saveOrUpdateCourse } from "@/api/course/course";
import classApi from "@/api/course/classroom";
export default {
    //import引入的组件需要注入到对象中才能使用
    name: "CourseInfo",
    components: { Tinymce },
    props: ["courseId", "classId"],
    data() {
        //这里存放数据
        return {
            course: {
                id: "",
                title: "",
                teacherId: "",
                teacherName: "",
                subjectId: "",
                subjectParentId: "",
                classId: "",
                price: 0.0,
                lessonNum: 0,
                cover: "",
                description: "",
            },
            subjects: [],
            childSubjects: [],
            //讲师搜索列表
            loading: false,
            teachers: [],
            BASE_API: process.env.BASE_API + "/oss/uploadPhoto",
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        getSubjects() {
            getSubject().then((response) => {
                this.subjects = response.data.cateGoryTree;
            });
        },
        parentSubjectChange(parentSubjectId) {
            for (let i = 0; i < this.subjects.length; i++) {
                if (this.subjects[i].id === parentSubjectId) {
                    this.childSubjects = this.subjects[i].children;
                    break;
                }
            }
        },

        //讲师搜索列表
        remoteMethod(query) {
            if (!this.classId) {
                if (query !== "") {
                    this.loading = true;
                    getTeacherByName(query).then((response) => {
                        this.teachers = response.data.teachers;
                        this.loading = false;
                    });
                } else {
                    this.teachers = [];
                }
            }
        },
        teacherChange(teacherId) {
            for (let i = 0; i < this.teachers.length; i++) {
                if (teacherId === this.teachers[i].id) {
                    this.course.teacherName = this.teachers[i].name;
                    break;
                }
            }
        },

        //课程封面
        handleAvatarSuccess(res, file) {
            // console.log(res); // 上传响应
            // console.log(URL.createObjectURL(file.raw)); // base64编码
            this.course.cover = res.data.url;
        },

        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/jpg";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
        getCourseInfo() {
            return new Promise((resolve) => {
                getCourseById(this.courseId, false, false).then((response) => {
                    this.course = response.data.course;
                    this.parentSubjectChange(this.course.subjectParentId);
                    //根据讲师id回显讲师列表
                    getById(this.course.teacherId).then((response) => {
                        this.teachers.push(response.data.teacher);
                        resolve();
                    });
                });
            });
        },
        saveOrUpdateCourse() {
            if (this.classId) {
                this.course.classId = this.classId;
            }
            saveOrUpdateCourse(this.course).then((response) => {
                this.course.id = response.data.courseId;
                this.$emit("mayChangeCourseId", this.course.id);
                this.$message({
                    message: "保存成功",
                    type: "success",
                });
            });
        },
        init() {
            this.getSubjects();
            if (this.courseId) {
                this.getCourseInfo();
            }
            if (this.classId) {
                classApi.getClassTeacher(this.classId).then((response) => {
                    let ts = response.data.teachers;
                    for (let i = 0; i < ts.length; i++) {
                        this.teachers.push({
                            id: ts[i].teacherId,
                            name: ts[i].name,
                            avatar: ts[i].avatar,
                            career: ts[i].career,
                        });
                    }
                    console.log("---", this.teachers);
                });
            }
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {},
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.init();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {
        this.$bus.$off("courseBus");
    }, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发，页面一旦激活就会触发
};
</script>
<style scoped>
</style>